import axios from "axios";
import { Message } from 'element-ui';
import store from "../store";
import localStorage from "../utilsCustomize/localStorage";
import router from "../router";

let // 时间戳字段
    timeLabel = [
        'addTime'
    ];

// axios 实例
const http = axios.create();

// 请求拦截器
http.interceptors.request.use(
    config => {

        let data,
            k;

        try {
            data = JSON.parse(JSON.stringify(config.data));
        } catch (e) {
            data = {};
        }

        for (k in data) {
            if (k === 'offset') {
                // 分页
                data[k] = (data[k] - 1) * data.length;
            } else if (timeLabel.includes(k)) {
                // 时间戳
                data[k] = parseInt(data[k] / 1000);
            }
        }

        config.data = data;
        config.headers.accesslogin = localStorage.get('accessLogin');
        config.baseURL = process.env.VUE_APP_BASE_URL;

        return config;
    },
    error => {
        console.log(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    response => {

        let data = response.data,
            dataData = data.data;

        // 登录
        if (dataData.accessLogin) localStorage.set('accessLogin', dataData.accessLogin);

        // 路由
        if (dataData.rules) store.commit('rulesMutations', dataData.rules);

        codeMessage(data);

        return data;
    },
    error => {
        console.log(error);
    }
);

// 提示错误信息
function codeMessage(data) {

    let msg = '';

    switch (data.code) {
        // 验证错误信息
        case 50000:
            msg = Object.values(data.data).shift();
            break;
        // 成功
        case 20000:
            break;
        // 登录信息出现异常
        case 80000:
            msg = data.message;
            localStorage.del('accessLogin');
            router.push({ name: 'Login' });
            break;
        // 其它错误信息
        default:
            msg = data.message;
            break;
    }

    if (msg !== '') {
        Message({
            showClose: true,
            message: msg,
            type: 'error'
        });
    }

}

export default http;